<?php

use Illuminate\Database\Capsule\Manager as DB;

class User_WalletController extends CommonController
{
    protected $authExcept = ['rechargeNotify'];

    // 按月份获取签到记录
    public function indexAction()
    {
        $params = $this->get();
        $wallet_type = $params['wallet_type'] ?? 'money';
        if (!in_array($wallet_type, ['money', 'score'])) {
            throw new Exception('参数错误');
        }
        $user = \app\service\auth::getUser();
        $status = $params['status'] ?? 'all';
        $date = isset($params['date']) ? explode('-', $params['date']) : [];
        if ($wallet_type == 'money') {
            $query = membermoneylogModel::where('member_id', $user->id);
        } else {
            $query = memberscorelogModel::where('member_id', $user->id);
        }
        if ($status != 'all') {
            $query->{$status}();
        }
        if (!empty($date)) {
            array_walk($date, function (&$item, $key) {
                $item = $key == 1 ? $item . ' 23:59:59' : $item;
                $item = timestamp(strtotime($item));
            });
            $query->whereBetween('created_at', $date);
        }
        // 收入
        $income = (clone $query)->where($wallet_type, '>', 0)->sum($wallet_type);

        // 支出
        $expend = (clone $query)->where($wallet_type, '<', 0)->sum($wallet_type);
        $page = $params['page'] ?? 1;
        $per_page = $params['per_page'] ?? 10;
        $total = $query->count();
        $data = $query->orderBy('id', 'DESC')->offset(($page - 1) * $per_page)->limit($per_page)->get();
        foreach ($data as &$w) {
            $w->avatar = $user->avatar;
            $w->createtime = strtotime($w->created_at);
            $w->type_name = $w->event_name;
            $w->title = $w->remark;
            $w->wallet = $w->$wallet_type;
            if ($w->event == 'orderget') {
                $order_sn = DB::table('order')->where('id', $w->event_id)->value('order_sn');
                $w->order_sn = $order_sn ?? '';
            }
        }
        $walletLogs = [
            'current_page' => $page,
            'last_page' => ceil($total / $per_page),
            'per_page' => $per_page,
            'total' => $total,
            'data' => $data,
        ];
       $is_tx = DB::table('sys_config')->where(['id'=>47])->value('value');
        json(['code' => 1, 'msg' => '获取成功', 'data' => [
            'wallet_logs' => $walletLogs,
            'income'      => $income,
            'expend'      => $expend,
            'is_tx'      => $is_tx
        ]]);
    }


    public function rechargeAction()
    {
        $params = $this->getPost();
        $platform = $params['platform'] ?? 'wxOfficialAccount';
        $payment = $params['payment'] ?? 'wechat';
        $money = $params['money'] ?? 0;
        if(!empty($params['order_id'])){
            $order = \app\modules\Admin\models\memberzmdapplyModel::where('id', $params['order_id'])->first();
            $money = $order->agent_fee;
            $subject = "专卖店申请";
            $notify_url = $this->config->application->hostUrl . '/user_wallet/rechargeNotify/payment/' . $payment.'/order_id/'.$params['order_id'];
            $param = "{'goods_id':1002}";
        }else{
            $subject = "钱包充值";
            $notify_url = $this->config->application->hostUrl . '/user_wallet/rechargeNotify/payment/' . $payment;
            $param = "{'goods_id':1001}";
        }
        if (!is_numeric($money) || $money <= 0) {
            throw new Exception('充值金额不合法');
        }

        $user = \app\service\auth::getUser();
        $oauth = memberoauthModel::where('member_id', $user->id)->first();
        if (!$oauth) {
            throw new Exception('缺少 openid');
        }

        $sn = 'wr' . $user->id . date('YmdHis') . mt_rand(100, 999);

        if(empty($params['order_id'])){
            memberwalletrechargeModel::insert([
                'member_id' => $user->id,
                'sn' => $sn,
                'money' => $money,
                'payment' => $payment,
            ]);
        }
        $pay = new PayService($payment, $platform, $notify_url);
        $result = $pay->create([
            'subject' => $subject,
            'out_trade_no' => $sn,
            'amount' => $money,
            'openid' => $oauth->openid,
            'param' =>	$param,
        ]);

        if (is_array($result)) {
            $result['ordersn'] = $sn;
        }

        json(['code' => 1, 'msg' => '获取预付款成功', 'data' => $result]);
    }

    public function rechargeNotifyAction()
    {
        Log::out('notifyx-recharge:' . file_get_contents("php://input"), 'recharge');
        $ordersn = $this->getPost('ordersn');
        Log::out("Notify wallet recharge ordersn {$ordersn}", 'notify');
        $payment = $this->getRequest()->getParam('payment', 'wechat');
        $platform = $this->getRequest()->getParam('platform', 'wxOfficialAccount');

        $orderid  = $this->get('order_id', '');
        if($orderid){
            DB::table('member_zmd_apply')->where('id', $orderid)->update(['agent_fee_pay_status'=>1,'updated_at'=>date('Y-m-d H:i:s')]);
        }else{
            (new PayService($payment, $platform))->notify('memberwalletrechargeModel', 'notifyProcess', $ordersn);
        }
    }

    public function getRechargeLogsAction()
    {
        $user = \app\service\auth::getUser();
        $data = memberwalletrechargeModel::where('member_id', $user->id)
            ->orderBy('id', 'desc')
            ->get();
        json(['code' => 1, 'msg' => '充值记录', 'data' => $data]);
    }

    // 提现规则
    public function ruleAction()
    {
        $data = memberwalletapplyModel::getWithdrawConfig();
        $data['methods'][1] = 'wechat';
//        $data['methods'][2] = 'alipay';

        json(['code' => 1, 'msg' => '提现规则', 'data' => $data]);
    }

    // 申请提现
    public function applyAction()
    {
        $params = $this->getPost();
//        $params['type']  = "image";
        try {
            Validate::check($params, [
                'type' => ['role'=>'required', 'msg'=>'提现方式'],
                'money' => ['role'=>'required', 'msg'=>'提现金额'],
                'paypwd' => ['role'=>'required', 'msg'=>'支付密码'],
            ]);
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
        $user = \app\service\auth::getUser();
        if (empty($user->pay_password)) {
            throw new Exception('请设置提现密码');
        }
        if (md5($params['paypwd']) != $user->pay_password) {
            throw new Exception('密码错误');
        }
        $apply = DB::transaction(function () use ($params) {

            return memberwalletapplyModel::apply($params['type'], $params['money'],$params['image']);
        });
        json(['code' => 1, 'msg' => '提现申请成功', 'data' => $apply]);
    }

    // 提现记录
    public function applyLogAction()
    {
        $params = $this->get();
        json(['code' => 1, 'msg' => '提现记录', 'data' => memberwalletapplyModel::getList($params)]);
    }

    // 转账
    public function transferAction()
    {
        $params = $this->getPost();
        $customerId = $params['customerId'] ?? '';
        $money = $params['money'] ?? '';
        $memo = $params['memo'] ?? '';
        $type = $params['type'] ?? 'money';
        $paypwd = $params['paypwd'] ?? '';
        $user = \app\service\auth::getUser();
        if (!$user->pay_password) {
            throw new Exception('请设置提现密码');
        }
        if (md5($paypwd) != $user->pay_password) {
            throw new Exception('支付密码错误');
        }

        // 是否允许转账
        $config = configModel::where('type', 9)
            ->whereIn('key', ['enable_transfer', 'only_team_transfer', 'only_up_to_down', 'exception'])
            ->pluck('value', 'key')
            ->toArray();
        $allow = $config['enable_transfer'] ?? 0;
        if (!$allow) {
            throw new Exception('不可转账');
        } else {
            $exception = explode(',', $config['exception'] ?? '');
            if (!in_array($user->id, $exception)) {
                $member_child = memberchildrenModel::where('member_id', $user->id)->where('children_id', $customerId)->first();
                if (!$member_child) {
                    $member_child = memberchildrenModel::where('children_id', $user->id)->where('member_id', $customerId)->first();
                }
                if (!empty($config['only_team_transfer']) && empty($member_child)) {
                    throw new Exception('仅允许同团队互转');
                }
                if (!empty($config['only_up_to_down']) && !($member_child->member_id == $user->id && $member_child->children_id == $customerId)) {
                    throw new Exception('仅允许上级转下级');
                }
            }
        }

        if ($type == 'money') {
            if ($money <= 0) {
                throw new Exception('转账余额非法');
            }
            if ($user->money < $money) {
                throw new Exception('账户余额不足');
            }
        }
        if ($type == 'score') {
            if ($money <= 0) {
                throw new Exception('转账能量非法');
            }
            if ($user->score < $money) {
                throw new Exception('能量余额不足');
            }
        }

        $customer = memberModel::find($customerId);
        if (!$customer) {
            throw new Exception('目标用户不存在');
        }

        $transfer_id = DB::transaction(function () use ($user, $customer, $money, $memo, $type) {
            $oper = \app\service\auth::setOper();
            $transfer_id = membertransferlogModel::insertGetId([
                'member_id' => $user->id,
                'target_id' => $customer['id'],
                'wallet' => $money,
                'wallet_type' => $type,
                'remark' => $memo . ' 从用户'.$user->id.'转账至用户'.$customer->id,
                'oper_type' => $oper['oper_type'],
                'oper_id' => $oper['oper_id'],
                'created_at' => timestamp(),
            ]);
            if ($type == 'score') {
                memberModel::score(-$money, $user->id, 'transfer_out', $transfer_id, '积分转出' . $money . '元至账户' . $customer['id'] . ':' . $customer['nickname']);
                memberModel::score($money, $customer['id'], 'transfer_in', $transfer_id, '积分转入' . $money . '元自账户' . $user->id . ':' . $user->nickname);
            }
            if ($type == 'money') {
                memberModel::money(-$money, $user->id, 'transfer_out', $transfer_id, '余额转出' . $money . '元至账户' . $customer['id'] . ':' . $customer['nickname']);
                memberModel::money($money, $customer['id'], 'transfer_in', $transfer_id, '余额转入' . $money . '元自账户' . $user->id . ':' . $user->nickname);
                return $user;
            }
            return $transfer_id;
        });
        if (!$transfer_id) {
            throw new Exception('转账失败');
        }
        json(['code' => 1, 'msg' => '转账成功', 'data' => $transfer_id]);
    }

    public function transferLogAction()
    {
        $params = $this->get();
        $data = membertransferlogModel::getList($params);
        json(['code' => 1, 'msg' => '获取成功', 'data' => $data]);
    }
}
